// import dbHelper from '../../../common/dbHelper'
import SQLite from '../../common/SQLiteHelper'
import sqlHelper from './editorSqlHelper'

// const fs = require('fs')

export default {
  async getSlideConfig () {
    try {
      let execSqls = {
        template: sqlHelper.getSlideTemplates,
        style: sqlHelper.getSlideStyles,
        cover: sqlHelper.getSlideCover,
        font: sqlHelper.getSlideFonts,
        animation: sqlHelper.getSlideAnimatios,
        defaultFiles: sqlHelper.getDefaultFiles
      }
      // 配置数据源
      var configSource = null

      if (process.browser) {
        configSource = {
          template: await SQLite.ExecuteReader(sqlHelper.getSlideTemplates),
          style: await SQLite.ExecuteReader(sqlHelper.getSlideStyles),
          cover: await SQLite.ExecuteReader(sqlHelper.getSlideCover),
          font: await SQLite.ExecuteReader(sqlHelper.getSlideFonts),
          animation: await SQLite.ExecuteReader(sqlHelper.getSlideAnimatios),
          defaultFiles: await SQLite.ExecuteReader(sqlHelper.getDefaultFiles)
        }
      } else {
        configSource = await SQLite.ExecuteReaders(execSqls)
      }

      let slideIDs = []
      // 组织查询幻灯片版式
      configSource.template.forEach((item) => {
        item.templateContent = []
        slideIDs.push(item.id)
      })
      // 组织查询幻灯片风格
      configSource.style.forEach((item) => {
        item.styleContent = []
        slideIDs.push(item.id)
      })
      // 查询风格版式对应幻灯片元素
      let slideSource = await this.getSlideElements(slideIDs)
      for (let name in slideSource) {
        let template = configSource.template.find((x) => {
          return x.id === name
        })
        if (template) {
          template.templateContent = slideSource[name]
          continue
        }
        let style = configSource.style.find((x) => {
          return x.id === name
        })
        if (style) style.styleContent = slideSource[name]
      }
      return configSource
    } catch (error) {
      throw error
    }
  },
  // 获取编辑区元素
  async getSlideElements (id) {
    try {
      let parameter = ''
      let arr = Array.isArray(id) ? id : [id]
      arr.forEach((item, index) => {
        parameter += arr.length - 1 === index ? `'${item}'` : `'${item}',`
      })

      let execSqls = {
        els: sqlHelper.getSlideElements(parameter),
        elStyles: sqlHelper.getSlideEleStyle(parameter),
        elAnimations: sqlHelper.getSlideEleAnimation(parameter),
        elZoom: sqlHelper.getSlideZoomEle(parameter)
      }
      let result = null
      if (process.browser) {
        result = {
          els: await SQLite.ExecuteReader(sqlHelper.getSlideElements(parameter)),
          elStyles: await SQLite.ExecuteReader(sqlHelper.getSlideEleStyle(parameter)),
          elAnimations: await SQLite.ExecuteReader(sqlHelper.getSlideEleAnimation(parameter)),
          elZoom: await SQLite.ExecuteReader(sqlHelper.getSlideZoomEle(parameter))
        }
      } else {
        result = await SQLite.ExecuteReaders(execSqls)
      }

      let dataSource = mergingDataSources(result.els, result.elStyles, result.elAnimations, result.elZoom)
      if (!Array.isArray(id)) {
        dataSource = dataSource ? dataSource[id] : []
      }
      return dataSource
    } catch (error) {
      throw error
    }
  },
  async addSlideStyle (parameter) {
    try {
      let execSqls = [sqlHelper.addSlideStyle(parameter)]
      execSqls = execSqls.concat(getSaveElementSql([parameter]))
      await SQLite.ExecuteNonQuery({executeSql: execSqls, isTransaction: true})
    } catch (error) {
      throw error
    }
  },
  async addSlideTemplate (parameter) {
    try {
      let execSqls = [sqlHelper.addSlideTemplate(parameter)]

      execSqls = execSqls.concat(getSaveElementSql([parameter]))
      // dbHelper.exec(execSqls);
      await SQLite.ExecuteNonQuery({executeSql: execSqls, isTransaction: true})
    } catch (error) {
      throw error
    }
  },
  async saveSlide (parameter) {
    try {
      return await SQLite.ExecuteNonQuery({executeSql: getSaveElementSql([parameter]), isTransaction: true})
    } catch (error) {
      throw error
    }
  },
  // 修改封面文本
  async setSlideCoverText (param) {
    try {
      return await SQLite.ExecuteNonQuery({executeSql: sqlHelper.setSlideCoverText(param)})
    } catch (error) {
      throw error
    }
  },
  // 删除外部文件
  async delExternalFile (id) {
    try {
      return await SQLite.ExecuteNonQuery(sqlHelper.delExternalFile(id))
    } catch (error) {
      throw error
    }
  },
  // 删除外部文件流
  async delExternalFileStream (param) {
    try {
      return await SQLite.ExecuteNonQuery({executeSql: [sqlHelper.delExternalFileStream(param)]})
    } catch (error) {
      throw error
    }
  },
  // 添加截图文件
  async addImageStream (param) {
    try {
      return await SQLite.ExecuteNonQuery({executeSql: sqlHelper.addImageStream(param), isTransaction: true})
    } catch (error) {
      throw error
    }
  },
  // 获取幻灯片内文件id
  async getSlideImgIDs (param) {
    try {
      return await SQLite.ExecuteReader(sqlHelper.getSlideImgIDs(param))
    } catch (error) {
      throw error
    }
  },
  // 修改幻灯片标题
  async eidtSlideTitle (param) {
    try {
      return await SQLite.ExecuteNonQuery(sqlHelper.eidtSlideTitle(param))
    } catch (error) {
      throw error
    }
  }
}

function mergingDataSources (els, elStyles, elAnimations, elZoom) {
  try {
    let dataSource = {}
    els.forEach((item) => {
      if (dataSource[item.sid] === undefined) {
        dataSource[item.sid] = []
      }
      item.isEdit = (/^true$/i).test(item.isEdit)
      item.lockHeight = (/^true$/i).test(item.lockHeight)
      item.lockWidth = (/^true$/i).test(item.lockWidth)
      item.lockMove = (/^true$/i).test(item.lockMove)
      item.lockSelect = (/^true$/i).test(item.lockSelect)
      item.templateElement = (/^true$/i).test(item.templateElement)
      item.show = (/^true$/i).test(item.show)
      item.width = parseFloat(item.width)
      item.height = parseFloat(item.height)
      item.left = parseFloat(item.left)
      item.top = parseFloat(item.top)
      let style = elStyles.find((s) => {
        return s.sid === item.sid && s.eid === item.id
      })
      item.style = style || {}
      delete item.style.sid
      delete item.style.eid

      item.animation = elAnimations.filter((a) => {
        return a.sid === item.sid && a.eid === item.id
      })
      item.zoom = elZoom.find((a) => {
        return a.sid === item.sid && a.eid === item.id
      })
      if (item.zoom) {
        item.zoom.zoomScale = parseFloat(item.zoom.zoomScale)
        item.zoom.top = parseFloat(item.zoom.top)
        item.zoom.left = parseFloat(item.zoom.left)
      }
      dataSource[item.sid].push(item)
    })
    return dataSource
  } catch (error) {
    throw error
  }
}

function getSaveElementSql (source) {
  let execSqls = []
  source.forEach((item) => {
    // 删除所有元素
    execSqls.push(sqlHelper.delAllElements(item.id))
    // 删除所有样式
    execSqls.push(sqlHelper.delAllEleStyle(item.id))
    // 删除所有动画
    execSqls.push(sqlHelper.delAllEleAnimation(item.id))
    // 删除所有缩放元素
    execSqls.push(sqlHelper.delAllEleZoom(item.id))

    // 添加元素
    item.elements.forEach((el) => {
      execSqls.push(
        sqlHelper.addSlideElement({
          sid: item.id,
          id: el.id,
          name: el.name,
          type: el.type,
          text: el.text,
          html: el.html,
          path: el.path,
          index: el.index,
          width: el.width,
          height: el.height,
          left: el.left,
          top: el.top,
          isEdit: el.isEdit,
          lockHeight: el.lockHeight,
          lockWidth: el.lockWidth,
          lockMove: el.lockMove,
          lockSelect: el.lockSelect,
          templateElement: el.templateElement,
          show: el.show,
          fileCode: el.fileCode ? el.fileCode : ''
        }))
      execSqls.push(
        sqlHelper.addElementStyle({
          sid: item.id,
          eid: el.id,
          fontfamily: el.style['font-family'] ? el.style['font-family'] : '',
          fontsize: el.style['font-size'] ? el.style['font-size'] : '',
          color: el.style['color'] ? el.style['color'] : '',
          fontweight: el.style['font-weight'] ? el.style['font-weight'] : '',
          fontstyle: el.style['font-style'] ? el.style['font-style'] : '',
          textdecoration: el.style['text-decoration'] ? el.style['text-decoration'] : '',
          textalign: el.style['text-align'] ? el.style['text-align'] : '',
          borderwidth: el.style['border-width'] ? el.style['border-width'] : '',
          borderstyle: el.style['border-style'] ? el.style['border-style'] : '',
          bordercolor: el.style['border-color'] ? el.style['border-color'] : '',
          backgroundcolor: el.style['background-color'] ? el.style['background-color'] : ''
        }))

      if (el.animation && el.animation.length) {
        el.animation.forEach((ani) => {
          execSqls.push(sqlHelper.addElementAnimation({sid: item.id, eid: el.id, aid: ani.id, time: ani.time}))
        })
      }

      if (el.zoom) {
        execSqls.push(sqlHelper.addElementZoom({sid: item.id, eid: el.id, ...el.zoom}))
      }
    })
  })
  return execSqls
}
